package com.damai.hotload;

import java.io.File;
import java.io.FileFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import com.citywithincity.interfaces.IService;


public class AppManager implements IService {
	public static URLClassLoader createClassLoader(ClassLoader parentClassLoader, File[] jarFiles) {
		List<URL> jarsToLoad = new ArrayList<URL>();
		for (File file : jarFiles) {
			try {
				jarsToLoad.add(file.toURI().toURL());
			} catch (MalformedURLException e) {
				throw new RuntimeException("Load jar file exception !",e);
			}
		}
		URL[] urls = new URL[jarsToLoad.size()];
		jarsToLoad.toArray(urls);
		return new URLClassLoader(urls, parentClassLoader);
	}
	
	
	private String rootPath;
	
	private App app;
	
	public AppManager(){
		
	}
	
	public String getRootPath() {
		return rootPath;
	}
	
	
	public void setRootPath(String rootPath) {
		this.rootPath = rootPath;
	}
	
	/**
	 * 
	 */
	@Override
	public void start(){
		stop();
		File[] files = new File(rootPath).listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith("jar");
			}
		});
		app = new App(createClassLoader(AppManager.class.getClassLoader(),files));
		try {
			app.start();
		} catch (HotLoadException e) {
			
		}
	}
	
	@Override
	public void stop() {
		if(app!=null){
			app.stop();
			app = null;
		}
	}
}
